package models

import (
	"fmt"
	"gin-blog/appconfig"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func Init() {

	var err error
	mysqlConfig := appconfig.Config.Mysql //读取数据库的配置
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConfig.User,     //用户名
		mysqlConfig.Password, //密码
		mysqlConfig.Host,     //ip
		mysqlConfig.Port,     //端口
		mysqlConfig.Database, //数据库
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql: init success")

	err = DB.AutoMigrate(&User{})
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql:  autoMigrate success")
}
